import { verify } from "@util/jwt";
import { jwtSecret } from "@config/config.default";
import { User } from "@model";
import { Handler } from "express";

export const auth: Handler = async (req, res, next) => {
  // 获取token
  let token = req.headers.authorization;
  token = token ? token.split("Bearer ")[1] : undefined;
  // 验证token
  if (!token) {
    return res.status(401).end();
  }
  try {
    const decodedToken = await verify(token, jwtSecret); // tslint:disable-line
    // 有效 -> 将用户信息挂载到req
    (req as any).user = await User.findById((decodedToken as any).userId);
    next();
  } catch (error) {
    // 无效 -> 响应401
    return res.status(401).end();
  }
};
